<?php

namespace App\Console\Commands;

use App\Models\ProjectPart;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Temperature extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'temperature:get';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 查询所有部位数据，并调用天气接口获取天气数据
        $part = ProjectPart::where('status', 1)->get();
        $date = date('Y-m-d');
        foreach ($part->toArray() as $val) {
            $url = 'https://yiketianqi.com/api?version=v62&appid=82532833&appsecret=pGt679pv';
            $url .= '&lat' . $val['latitude'];
            $url .= '&lng=' . $val['longitude'];
            $result = curl_get($url);
            $result = json_decode($result, true);
            $data = [
                'tem'        => $result['tem'],
                'win'        => $result['win'],
                'air'        => $result['air'],
                'part_id'    => $val['id'],
                'tem_max'    => $result['tem1'],
                'tem_min'    => $result['tem2'],
                'win_speed'  => $result['win_speed'],
                'win_meter'  => $result['win_meter'],
                'humidity'   => $result['humidity'],
                'visibility' => $result['visibility'],
                'pressure'   => $result['pressure'],
                'air_level'  => $result['air_level'],
                'remarks'    => json_encode($result['aqi']),
                'air_tips'   => $result['air_tips'],
                'record_date'=> $date,
                'project_id' => $val['project_id'],
            ];
            DB::table('temperatures')->insert($data);
        }

        // TODO 业务
        Log::info('部位气温获取完成：' . date('Y-m-d H:i:s'));
    }
}
